package com.moyun.controller;

import com.moyun.model.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SysResouceController
 * @Description 系统资源控制层
 * @Author yangboxuan
 * @Date 2022/6/23 21:39
 */
@Api(tags = {"系统资源数据"})
@ApiIgnore
@RestController
@RequiredArgsConstructor
public class SysResouceController {

    private ApplicationContext applicationContext;

    @GetMapping("/getAllURIs")
    @ApiOperation(value = "获取系统中的所有URI")
    public R<List<Map<String, String>>> getAllURIs() {
        RequestMappingHandlerMapping mapping = this.applicationContext.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();

        List<Map<String, String>> list = new ArrayList<>();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
            Map<String, String> mapTemp = new HashMap<>();
            addURIMetaData(list, m, mapTemp);
        }

        return R.ok(list);
    }

    private void addURIMetaData(List<Map<String, String>> list, Map.Entry<RequestMappingInfo, HandlerMethod> m, Map<String, String> map) {
        RequestMappingInfo info = m.getKey();
        HandlerMethod method = m.getValue();
        PatternsRequestCondition p = info.getPatternsCondition();
        for (String url : p.getPatterns()) {
            map.put("url", url);
        }
        map.put("className", method.getMethod().getDeclaringClass().getName());
        map.put("method", method.getMethod().getName());
        RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
        for (RequestMethod requestMethod : methodsCondition.getMethods()) {
            map.put("type", requestMethod.toString());
        }

        list.add(map);
    }

}
